package com.coolgor.coldot.web.wechat.qyh;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.coolgor.coldot.enums.auth.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.coolgor.xutil.Net.HttpServletRequestUtil;
import com.coolgor.coldot.dto.auth.LocalUserExecution;
import com.coolgor.coldot.dto.auth.RoleExecution;
import com.coolgor.coldot.dto.wechat.qyh.QYHAccessTokenExecution;
import com.coolgor.coldot.dto.wechat.qyh.QYHUserExecution;
import com.coolgor.coldot.entity.auth.LocalUser;
import com.coolgor.coldot.entity.auth.LoginInfo;
import com.coolgor.coldot.entity.auth.Role;
import com.coolgor.coldot.entity.wechat.qyh.QYHUser;
import com.coolgor.coldot.enums.wechat.qyh.QYHAccessTokenStateEnum;
import com.coolgor.coldot.enums.wechat.qyh.QYHUserStateEnum;
import com.coolgor.coldot.service.auth.LocalUserService;
import com.coolgor.coldot.service.auth.LoginInfoService;
import com.coolgor.coldot.service.auth.RoleService;
import com.coolgor.coldot.service.wechat.qyh.QYHAccessTokenService;
import com.coolgor.coldot.service.wechat.qyh.QYHUserService;
import com.coolgor.coldot.common.wechat.qyh.WechatQYHUtil;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 获取关注公众号之后的微信用户信息的接口，如果在微信浏览器里访问
 * https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd7f6c5b8899fba83&redirect_uri=http://o2o.yitiaojieinfo.com/o2o/wechatlogin/logincheck&role_type=1&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect
 * https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf5124501c044efec&redirect_uri=http://www.lordforce.com/axnut/wechatlogin/logincheck&role_type=1&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect
 * https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxef31de7a23359e19&redirect_uri=http://www.lordforce.com/axnut/wxqyhlogin/logincheck&response_type=code&scope=snsapi_base&state=1#wechat_redirect
 * 则这里将会获取到code,之后再可以通过code获取到access_token 进而获取到用户信息
 * 
 * @author CoolGor
 *
 */
@Controller
@RequestMapping("wxqyhlogin")
public class WechatQYHLoginController {

	private static Logger log = LoggerFactory.getLogger(WechatQYHLoginController.class);
	
	@Autowired
	private QYHAccessTokenService qyhAccessTokenService;
	@Autowired
	private QYHUserService qyhUserService;
	@Autowired
	private LocalUserService localUserService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private LoginInfoService loginInfoService;
	

	@RequestMapping(value="/logincheck", method={RequestMethod.GET}, produces= {"application/json;charset=UTF-8"})
	@ResponseBody
	//@JsonIgnoreProperties(ignoreUnknown = true)//用ObjectMapper转换json对象时，忽略不存在的字段。
	public String doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		log.debug("wxqyh login get...");
		// 获取微信公众号传输过来的code,通过code可获取access_token,进而获取用户信息
		String code = request.getParameter("code");
		// 这个state可以用来传我们数据库中约定的record ID
		String state = request.getParameter("state");
		String[] states = state.split("/");
		String recordId = state;
		String jumpto = "";
		if (states.length>=2) {
			recordId = states[0];
			jumpto = states[1];
		} else if(states.length<2) {
			recordId = state;
		}
		String path = "/index.html";
		switch (jumpto) {
			case "coldot" :
				path = "/coldot/index.html";
				break;
			case "Friday" :
				path = "/index.html";
				break;
			case "shuobao" :
				path = "/scmis/index.html";
				break;
		}
		log.debug("wxqyh login code:" + code + " , recordId:" + recordId);
		if (null==code || null == recordId) {
			return "请从微信企业号或认证系统登录！";
		}
		QYHAccessTokenExecution ate = qyhAccessTokenService.getQYHAccessToken(Long.parseLong(recordId));
		String accessToken = null;
		if (ate.getState()==QYHAccessTokenStateEnum.SUCCESS.getState()) {
			accessToken = ate.getQyhAccessToken().getAccessToken();
		} else {
			return "Errer in get AccessToken !";
		}
		String userid = WechatQYHUtil.getQYHUserID(accessToken, code);
		String userInfo = WechatQYHUtil.getQYHUserInfo(accessToken, userid);
		//利用Jackson.databind工具，将requst里面的json内容转换成shop对象 
		ObjectMapper objectMapper = new ObjectMapper();
		QYHUser qyhUser = null;
		LocalUser localUser = null;
		try {
			//设置ObjectMapper在构建对象时，忽略不存在的字段
			objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
			 Map<?, ?> mapper = objectMapper.readValue(userInfo, Map.class);
			 if ( mapper.size()!=0 ) {
				 qyhUser = new QYHUser();
				 qyhUser.setUserid(mapper.get("userid").toString());
				 qyhUser.setCorpid(ate.getQyhAccessToken().getCorpId());
				 qyhUser.setName(mapper.get("name").toString());
				 qyhUser.setMobile(mapper.get("mobile").toString());
				 qyhUser.setDepartment(mapper.get("department").toString());
				 qyhUser.setPriority(mapper.get("order").toString());
				 qyhUser.setPosition(mapper.get("position").toString());
				 qyhUser.setGender(mapper.get("gender").toString());
				 qyhUser.setEmail(mapper.get("email").toString());
				 qyhUser.setIsleader(mapper.get("isleader").toString());
				 qyhUser.setAvatar(mapper.get("avatar").toString());
				 qyhUser.setTelephone(mapper.get("telephone").toString());
				 qyhUser.setEnable(mapper.get("enable").toString());
				 qyhUser.setAlias(mapper.get("alias").toString());
				 qyhUser.setExtattr(mapper.get("extattr").toString());
				 qyhUser.setStatus(Integer.valueOf(mapper.get("status").toString()));
				 qyhUser.setQRcode(mapper.get("qr_code").toString());
				 //这两个参数不知道为啥获取不成功，后续再调试
				 //qyhUser.setExternalPosition(mapper.get("external_position").toString());
				 //qyhUser.setExternalProfile(mapper.get("external_profile").toString());				 
			 }else {			
				 modelMap.put("success", false);
				 modelMap.put("errMsg", "创建 QYH user mapper 失败");
				 return modelMap.toString();
			 }			 
		} catch (Exception e) {
			modelMap.put("success", false);
			modelMap.put("errMsg", e.getMessage());
			return modelMap.toString();
		}
		//检查本地数据库是否已经存有该企业号用户数据
		QYHUser qyhUserInDB = qyhUserService.getQYHUser(qyhUser.getUserid(), qyhUser.getCorpid());
		if (null != qyhUserInDB) {
			//如果已经存有，则更新数据库中qyhuser信息和读取对应localuser信息出来
//			qyhUser = qyhUserInDB;
			qyhUser.setUserID(qyhUserInDB.getUserID());//同步本地数据库的USERID号，不然一会更新数据会出错
			QYHUserExecution qyhUE = qyhUserService.modifyQYHUser(qyhUser);
			if (qyhUE.getState()!=QYHUserStateEnum.SUCCESS.getState()) {
				modelMap.put("success", false);
				modelMap.put("errMsg", "更新企业微信的用户信息失败");
				return modelMap.toString();
			}
			localUser = localUserService.getLocalUser(qyhUser.getUserID());
			//将企业号中的部门信息更新到本地用户的部门信息
		} else {
			//如果不存在，则将获取到的信息插入数据库，同时创建一个本地用户。
			localUser =new LocalUser();
			localUser.setUsername("TEMP_"+qyhUser.getCorpid()+"_"+qyhUser.getUserid());
			localUser.setPassword("TEMP_"+qyhUser.getCorpid()+"_"+qyhUser.getUserid());
			localUser.setNameCN(qyhUser.getName());
			localUser.setMobilephone(qyhUser.getMobile());
			localUser.setEmail(qyhUser.getEmail());
			localUser.setGender(GenderEnum.UNKNOWN.getState());
			localUser.setStatus(LocalUserStateEnum.UNREGISTER.getState());
			LocalUserExecution localUE = localUserService.addLocalUser(localUser);
			if (localUE.getState()== LocalUserOperationStateEnum.SUCCESS.getState()) {
				qyhUser.setUserID(localUE.getLocalUser().getUserID());
				QYHUserExecution qyhUE = qyhUserService.addQYHUser(qyhUser);
				if (qyhUE.getState()!=QYHUserStateEnum.SUCCESS.getState()) {
					localUserService.removeLocalUser(localUser);
					modelMap.put("success", false);
					modelMap.put("errMsg", "创建本地用户信息失败");
					return modelMap.toString();
				}
			} else if (localUE.getState()==LocalUserOperationStateEnum.EXISTUSERNAME.getState()) {
				localUser.setUsername(localUser.getUsername()+System.currentTimeMillis());
				localUE = localUserService.addLocalUser(localUser);
				qyhUser.setUserID(localUE.getLocalUser().getUserID());
				QYHUserExecution qyhUE = qyhUserService.addQYHUser(qyhUser);
				if (qyhUE.getState()!=QYHUserStateEnum.SUCCESS.getState()) {
					localUserService.removeLocalUser(localUser);
					modelMap.put("success", false);
					modelMap.put("errMsg", "创建本地用户信息失败");
					return modelMap.toString();
				}
			}
		}
		//获取用户的角色
		List<Role> roleList = new ArrayList<Role>();
		Role loginRole = new Role();
		RoleExecution roleExe = roleService.getRoleListByUser(localUser);
		if (roleExe.getState()== RoleStateEnum.SUCCESS.getState() && roleExe.getCount()>0) {
			//如果能正常获取用户的角色列表
			roleList = roleExe.getRoleList();
			loginRole = roleList.get(0);
		} else {
			loginRole.setRoleID(9999L);
			loginRole.setRoleName("企业号临时角色");
			roleList.add(loginRole);
		}
		
		//制作登录日志信息
		LoginInfo loginInfo = new LoginInfo();
		loginInfo.setUserID(localUser.getUserID());
		loginInfo.setUsername(localUser.getUsername());
		loginInfo.setNameCN(localUser.getNameCN());
		loginInfo.setLoginRoleId(loginRole.getRoleID());
		loginInfo.setLoginRoleName(loginRole.getRoleName());
		loginInfo.setLoginIP(HttpServletRequestUtil.getIP(request));
		loginInfo.setLoginWay(LoginStateEnum.WECHAT_QYH.getStateInfo());
		loginInfo.setRemark(ate.getQyhAccessToken().getCorpName()+ate.getQyhAccessToken().getAgentId()+ate.getQyhAccessToken().getAgentName());
		//判断用户状态
		if (localUser.getStatus()==LocalUserStateEnum.UNREGISTER.getState()) {
			//如果用户状态为未注册
			loginInfo.setStatus(LoginStateEnum.DENIAL.getState());
			loginInfo.setStatusInfo(LoginStateEnum.DENIAL.getStateInfo());
			loginInfo.setRemark("[本地用户未注册]"+loginInfo.getRemark());
			//将本次登录日志写入数据库中
			loginInfoService.addLoginInfo(loginInfo);
			return "用户未注册，登录失败！";
		}else if (localUser.getStatus()==LocalUserStateEnum.UNACTIVE.getState()) {
			//如果用户状态为未激活
			loginInfo.setStatus(LoginStateEnum.DENIAL.getState());
			loginInfo.setStatusInfo(LoginStateEnum.DENIAL.getStateInfo());
			loginInfo.setRemark("[本地用户未激活]"+loginInfo.getRemark());
			//将本次登录日志写入数据库中
			loginInfoService.addLoginInfo(loginInfo);
			return "用户未激活，登录失败！";
		}else if (localUser.getStatus()==LocalUserStateEnum.ACTIVE.getState()) {
			//如果用户状态为正常
			loginInfo.setStatus(LoginStateEnum.LOGINSUCCESS.getState());
			loginInfo.setStatusInfo(LoginStateEnum.LOGINSUCCESS.getStateInfo());
		}else if (localUser.getStatus()==LocalUserStateEnum.DENIAL.getState()) {
			//如果用户状态为禁用
			loginInfo.setStatus(LoginStateEnum.DENIAL.getState());
			loginInfo.setStatusInfo(LoginStateEnum.DENIAL.getStateInfo());
			loginInfo.setRemark("[本地用户未激活]"+loginInfo.getRemark());
			//将本次登录日志写入数据库中
			loginInfoService.addLoginInfo(loginInfo);
			return localUser.getUsername()+"已被禁用<br>登录失败！";
		}
		//将本次登录日志写入数据库中
		loginInfoService.addLoginInfo(loginInfo);
		//将当前用户信息推入session
		request.getSession().setAttribute("qyh_user",qyhUser);
		request.getSession().setAttribute("login_user",localUser);
		request.getSession().setAttribute("role_list",roleList);
		request.getSession().setAttribute("login_role",loginRole);
		modelMap.put("qyh_user", qyhUser);
		modelMap.put("login_user", localUser);
		modelMap.put("success", true);			
//		PrintWriter out = response.getWriter();
//		out.println("<html>");
//		out.println("<script>");
//		out.println("window.open ('" + request.getContextPath() + "/airuc/mobile/index.html')");
//		out.println("</script>");
//		out.println("</html>");
		response.sendRedirect(request.getContextPath() + path);	
		return modelMap.toString();
	}
	
	
	
}
